﻿using System.Net;
using System.Net.Sockets;
using System.Text;


const int port = 9000;

var serverEndpoint = new IPEndPoint(IPAddress.Any, port);
var serverSocket = new UdpClient(serverEndpoint);
Console.WriteLine($"服务器已启动，正在监听端口 {port}...");

try
{
    while (true)
    {
        var clientEndpoint = new IPEndPoint(IPAddress.Any, 0);
        var clientRequestBytes = serverSocket.Receive(ref clientEndpoint);
        var clientRequest = Encoding.UTF8.GetString(clientRequestBytes);

        Console.WriteLine($"接收到来自客户端 {clientEndpoint.Address}:{clientEndpoint.Port} 的请求：{clientRequest}");

        const string serverResponse = "服务器已收到请求。";
        var serverResponseBytes = Encoding.UTF8.GetBytes(serverResponse);

        serverSocket.Send(serverResponseBytes, serverResponseBytes.Length, clientEndpoint);
        Console.WriteLine($"已发送响应给客户端 {clientEndpoint.Address}:{clientEndpoint.Port}：{serverResponse}\n");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"发生异常：{ex.Message}");
}
finally
{
    serverSocket.Close();
    Console.WriteLine("服务器已停止。");
}